package com.chen.interceptor;

import com.chen.utils.Constants;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RoleInterceptor extends HandlerInterceptorAdapter {

    //static final String[] COMMON_URL = {"/login.html", "logout.html"};
    static final String[] ADMIN_URL = {"/admin/.*"};
    static final String[] STUDENT_URL = {"/student/.*"};
    static final String[] TEACHER_URL = {"/teacher/.*"};

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer userType = (Integer) request.getSession().getAttribute(Constants.USER_TYPE);
        //查看当前获得的type
        String path = request.getServletPath();
        if(userType == null){
            response.sendRedirect("/login.jsp");
            return false;
        }
        //对角色进行判断
        if(userType==1){
            check(ADMIN_URL, path);
            return true;
        }else if (userType==2){
            check(TEACHER_URL, path);
            return true;
        }else if(userType==3){
            check(STUDENT_URL, path);
            return true;
        }
        return false;
    }

    public boolean check(String[] urls, String path) {
        for (String s : urls) {
            if (!path.matches(s)) {
                return false;
            }
        }
        return true;
    }

}
